﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace Thesis_v01
{
   public partial class ViewResults : Form
   {
      private static int waitTime = 5000;

      private GraphResponses graph;
      private QuestionDetail selectedQuestion;
      private bool runRetrieval;
      //private int counter;
      private int questionID;
      private int startingID;
      private ArrayList questions;
      private ArrayList responses;

      public ViewResults(int lessonID)
      {
         InitializeComponent();

         runRetrieval = false;
         startingID = 0;
         responses = new ArrayList();
         //counter = 0;

         LoadLessonQuestions(lessonID);
      }

      private void LoadLessonQuestions(int lessonID)
      {
         DBConnection dbConn = new DBConnection();
         ArrayList lessonQuestions = dbConn.RetrieveQuestions(lessonID);

         ListExistingQuestions(lessonQuestions);
      }

      public void ListExistingQuestions(ArrayList questionDetails)
      {
         questions = questionDetails;
         questionListView.Items.Clear();

         foreach (QuestionDetail question in questionDetails)
         {
            ListViewItem tempItem = questionListView.Items.Add(question.Number.ToString());
            tempItem.SubItems.AddRange(new string[] {
               question.Type.ToString(),
               question.Question});
         }

         questionListView.Refresh();
      }

      private void RunRetrieval()
      {
         if (retrieveToolStripButton.Text == "Start Retrieval")
         {
            if (questionListView.SelectedIndices.Count > 0)
            {
               //if (!runRetrieval)
               if (!backgroundWorker.IsBusy)
               {
                  int selectedIndex = questionListView.SelectedIndices[0];
                  selectedQuestion = (QuestionDetail)questions[selectedIndex];
                  questionID = selectedQuestion.ID;
                  retrieveToolStripButton.Text = "Stop Retrieval";
                  graphToolStripButton.Enabled = true;
                  graphToolStripButton.Text = "Graph Q" + selectedQuestion.Number + " Responses";
                  //RunRetrieval();
                  startingID = 0;

                  //Monitor.PulseAll(this);
                  responseListView.Items.Clear();
                  responses = new ArrayList();
                  InitGraph();
                  backgroundWorker.RunWorkerAsync();
               }
               else
               {
                  retrieveToolStripButton.Text = "Stopping...";
                  retrieveToolStripButton.Enabled = false;
               }
            }
         }
         else
         {
            if (backgroundWorker.IsBusy)
            {
               //retrieveToolStripButton.Text = "Start Retrieval";
               retrieveToolStripButton.Text = "Stopping...";
               retrieveToolStripButton.Enabled = false;
               backgroundWorker.CancelAsync();
            }
         }

         ToggleResponseRetrieval();
      }

      public void ToggleResponseRetrieval()
      {
         runRetrieval = !runRetrieval;
      }

      private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
      {
         DBConnection dbConn = new DBConnection();
         dbConn.OnlyOpenConnection();

         while (runRetrieval)
         {
            if (backgroundWorker.CancellationPending)
            {
               e.Cancel = true;
               break;
            }

            int maxResponseID = dbConn.FindMaxResponseID();
            //Console.WriteLine(questionID);
            Console.WriteLine(startingID);
            Console.WriteLine(maxResponseID);

            if (startingID < maxResponseID)
            {
               ArrayList response = dbConn.RetrieveOneResponse(questionID, startingID);
               //Console.WriteLine(response[0].ToString());

               if (response[0].ToString() != String.Empty)
               {
                  ResponseDetail newResponse = new ResponseDetail();
                  newResponse.ID = Int32.Parse(response[0].ToString());
                  newResponse.QuestionID = Int32.Parse(response[1].ToString());
                  newResponse.Description = response[2].ToString();

                  backgroundWorker.ReportProgress(0, newResponse);

                  Thread.Sleep(25);

                  //counter++;
                  startingID++;
               }
               else
               {
                  Thread.Sleep(waitTime);
               }
            }
            else
            {
               startingID = maxResponseID;
               Thread.Sleep(waitTime);
            }
         }

         dbConn.OnlyCloseConnection();
      }

      private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
      {
         retrieveToolStripButton.Text = "Start Retrieval";
         retrieveToolStripButton.Enabled = true;

         if (responses.Count > 0)
         {
            graphToolStripButton.Enabled = true;
         }
      }

      private void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
      {
         ResponseDetail response = (ResponseDetail)e.UserState;
         responses.Add(response);
         responseListView.Items.Add(response.Description);
         //responseListView.Items.Add(e.UserState.ToString());
         if (graph != null)
         {
            if (graph.Visible)
            {
               graph.CreateGraph(selectedQuestion, responses);
               //graph.Refresh();
            }
         }
      }

      private void retrieveToolStripButton_Click(object sender, EventArgs e)
      {
         RunRetrieval();
      }

      private void questionListView_SelectedIndexChanged(object sender, EventArgs e)
      {
         if ((!runRetrieval) && (!backgroundWorker.IsBusy))
         {
            if (questionListView.SelectedIndices.Count > 0)
            {
               retrieveToolStripButton.Enabled = true;
               if (responses.Count > 0)
               {
                  graphToolStripButton.Enabled = true;
               }
               startingID = 0;
               responses = new ArrayList();
            }
            else
            {
               retrieveToolStripButton.Enabled = false;
               graphToolStripButton.Enabled = false;
            }
         }
      }

      private void questionListView_DoubleClick(object sender, EventArgs e)
      {
         if (questionListView.SelectedIndices.Count > 0)
         {
            RunRetrieval();
         }
      }

      private void graphToolStripButton_Click(object sender, EventArgs e)
      {
         InitGraph();
      }

      private void InitGraph()
      {
         if (questionListView.SelectedIndices.Count > 0)
         {
            int selectedIndex = questionListView.SelectedIndices[0];
            selectedQuestion = (QuestionDetail)questions[selectedIndex];
            //questionID = selectedQuestion.ID;

            graph = new GraphResponses();
            graph.MdiParent = this.MdiParent;
            graph.Text = "Question " + selectedQuestion.Number;
            graph.CreateGraph(selectedQuestion, responses);

            graph.Show();
         }
      }

      private void ViewResults_FormClosing(object sender, FormClosingEventArgs e)
      {
         if (backgroundWorker.IsBusy)
         {
            backgroundWorker.CancelAsync();
         }
         MainApp main = (MainApp)this.MdiParent;
         main.ToggleResponseButtonEnable();
         //main.ToggleCourseListEnable();
         //main.ToggleEditCourseButtonEnable();
      }
   }
}
